<template>
  <!-- 当点击 取消按钮 时，关闭弹窗 -->
  <el-dialog :title="$t('printBoxCode.reprint')" :visible.sync="visible" width="60%" top="4vh" :append-to-body="true" @close="clearDialog()" v-loading="loding" :close-on-click-modal="false">
    <ele-form v-model="dialogfrom" v-bind="formConfig" ref="form"> </ele-form>
    <barcode-print :barcodeInfo="barcodeInfo" ref="print" :isPrint="false" :key="time" v-if="Object.keys(barcodeInfo).length > 0"></barcode-print>
    <div slot="footer" class="dialog-footer">
      <el-button @click="clearDialog()">{{ $t('common.cancel') }}</el-button>

      <el-button v-if="dialogfrom.type == 1" type="primary" @click="handleSave" :loading="loadingBtn">{{ $t('common.save') }}</el-button>
      <el-button v-else :disabled="!dialogfrom.quantity" type="primary" @click="handleRequest">{{ $t('printBoxCode.previewBarcode') }}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { barcodePrintingList2, printTemplateInfo, selectListByConfigurationCode } from '@/api/print/mesProdOrder'
import BarcodePrint from '@/components/barcodePrint/barcodePrint'
import { reprintSel, reprintSelList, mesProdOthercodeReprintList } from '@/api/print/mesProdOthercode'
import { getDict } from '@/api/common'
import qs from 'qs'
export default {
  name: 'barcodePrintingAddModel',
  watch: {
    visible(val, oldVal) {
      if (!val) {
        this.$nextTick(() => {
          this.$refs.form.resetForm()
        })
        this.barcodeInfo = {}
      }
    }
  },
  props: {
    title: {
      type: String,
      default: ''
    }
  },
  components: { BarcodePrint },
  data() {
    let that = this
    return {
      loding: false,
      time: 0,
      formConfig: {
        span: 24,
        isShowBackBtn: false,
        isShowSubmitBtn: false,
        labelPosition: 'right',
        formDesc: {
          orderCode: {
            type: 'input',
            label: $i18n.t('mesOtherCodePrinting.orderCode'),
            layout: 12,
            required: true,
            disabled: true,
            attrs: {
              stepStrictly: true,
              controlsPosition: 'right',
              min: 1
            }
          },
          prodCode: {
            type: 'input',
            label: $i18n.t('mesOtherCodePrinting.prodCode'),
            layout: 12,
            required: true,
            disabled: true
          },
          prodName: {
            type: 'input',
            label: $i18n.t('mesOtherCodePrinting.prodName'),
            layout: 12,
            required: true,
            disabled: true
          },
          codeType: {
            type: 'select',
            label: $i18n.t('mesOtherCodePrinting.codeType'),
            layout: 12,
            prop: {
              value: 'value',
              text: 'description'
            },
            options: async (data) => {
              const list = await getDict('mes_code_type')
              return list.data.result
            },
            required: true,
            disabled: true
          },
          quantity: {
            type: 'input',
            label: $i18n.t('mesOtherCodePrinting.printQuantity'),
            layout: 12,
            disabled: true,
            required: true
          },
          startBarCode: {
            type: 'input',
            label: $i18n.t('mesOtherCodePrinting.startBarcode'),
            layout: 24,
            required: true
          },
          endBarCode: {
            type: 'input',
            label: $i18n.t('mesOtherCodePrinting.endBarcode'),
            layout: 24,
            required: true
          }
          // printingTimes: {
          //   type: 'input',
          //   label: $i18n.t('mesProdOtherCode.printingTimes'),
          //   layout: 24,
          //   disabled: true
          // }
        }
      },
      barcodeInfo: {},
      dialogfrom: {},
      visible: false,
      loading: false,
      list: [],
      arrBarcodePrintingList2: [],
      loadingBtn: false
    }
  },
  methods: {
    // 初始化
    init(params) {
      console.log('11params', params)
      this.dialogfrom = params
      this.barcodeInfo = params
      this.visible = true
      this.dialogfrom.printQuantity = this.dialogfrom.quantity //条码数量=计划数量
      this.reprintSel()

      this.$nextTick(() => {
        this.handleChange(params.barcodePrintTemp)
      })
    },

    /**
     * @author bing
     * @since 2022-11-17 14:44:33
     *  获取补打信息
     */
    async reprintSel() {
      const res = await reprintSel({
        orderCode: this.dialogfrom.orderCode,
        codeType: this.dialogfrom.codeType
      })
      this.$nextTick(() => {
        this.dialogfrom = {
          startBarCode: '',
          endBarCode: '',
          ...this.dialogfrom,
          ...res.data.result
        }
      })
    },
    // 条码模板选择
    handleChange(e) {
      if (this.arrBarcodePrintingList2.length == 0) return
      if (!this.dialogfrom.barcodePrintTemp) return

      let obj = this.arrBarcodePrintingList2.find((ite) => {
        return e == ite.templateName
      })
      this.loading = true
      printTemplateInfo(obj.id)
        .then((res) => {
          this.time = new Date().getTime()
          this.barcodeInfo = { ...this.barcodeInfo, ...res.data.result }
        })
        .finally((res) => {
          this.loading = false
        })
    },
    clearDialog() {
      this.visible = false
      this.$emit('refreshList')
    },
    // 点击打印按钮
    handleRequest() {
      // if (this.dialogfrom.printingTimes == 0) {
      //   this.$message.warning($i18n.t('printBoxCode.unableToPrint'))
      //   return
      // }
      this.$refs.form.handleSubmitForm()

      this.$refs.form.validate().then((valid) => {
        const { orderCode, codeType, startBarCode, endBarCode } = this.dialogfrom
        const data = {
          orderCode,
          codeType,
          startBarCode,
          endBarCode
        }
        reprintSelList(data).then((res) => {
          if (res.data.success) {
            let list = res.data.result,
              info = this.barcodeInfo,
              infoList = []
            if (Array.isArray(list) && list.length > 0) {
              list.forEach((item) => {
                infoList.push(item)
              })
            }
            delete info.values
            // ----条码打印多份（条码数量根据打印次数printingTimes重新计算）----
            let newInfoList = []
            infoList.forEach((v) => {
              newInfoList = [...newInfoList, ...Array(Number(this.dialogfrom.printingTimes)).fill(v)]
            })
            info.values = newInfoList
            localStorage.splitPrint = JSON.stringify(info)

            this.clearDialog()
            window.open('/mom/component/mes/splitPrint?type=10')
          }
        })
      })
    },

    // 点击保存按钮
    handleSave() {
      this.$refs.form.validate().then((valid) => {
        this.loadingBtn = true
        const { orderCode, codeType, startBarCode, endBarCode } = this.dialogfrom
        const data = {
          orderCode,
          codeType,
          startBarcode: startBarCode,
          endBarcode: endBarCode
        }
        mesProdOthercodeReprintList(data)
          .then((res) => {
            this.loadingBtn = false
            this.visible = false
            this.$parent.$refs.repairPrintTables.refresh()
          })
          .finally((error) => {
            this.loadingBtn = false
          })
      })
    }
  },
  async created() {
    let list = await barcodePrintingList2()
    this.arrBarcodePrintingList2 = list.data.result || []
  }
}
</script>
